<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="cn.com.dhcc.ddi.task.service.transform.FunctionAction" %>
<%@ include file="/WEB-INF/view/common/taglibs.jsp"%>
<%@ include file="/WEB-INF/view/common/css_js_ace.jsp"%>
<script type="text/javascript">
/**
 * 选择映射规则
 */
function dataMappingRuleChoose(){
	$.ajax({
		   type: "GET",
		   dataType:"html",
		   cache: false,
		   url: _ctx + "/data_mapping/data_mapping_rule_choose.do",
		   data: {
			   srcDsId:$("#srcDsId").val(),
			   mappingType:window.content.$('input[name="mappingType"]:checked').val() 
	       },
		   beforeSend : function(){
	       },
		   success: function(content){
			   
			   $(window.content.document.getElementById('dataMappingChooseDiv')).html(content);
					var hiddenByClick = false;
					window.parent.iframeModal("dataMappingChooseModal", $(window.content.document.getElementById('dataMappingChooseModal')).html(), hiddenByClick);
		   },
		   error:function(){
			   parent.ui.msg( '请求发送失败！',0 );
		   }
	});
}

/**
 * 保存信息
 */
function saveInfo(){
	$('#inputForm input').tooltip();
	$('#inputForm').checkForm();
	var checkReturn = $('#inputForm').checkForm(null, false);
	$("#chooseFxVerify").next().css("margin-top","-5px");
	if(checkReturn){
		var mappingModel = $($("#detailedFxInfo #mappingModel")[0]).text();
		var argContentLength = $("#argContentLength").val();
		var fxIdStr = $("#fxIdStr").val();
		var fxTypeStr = $("#fxTypeStr").val();
		var tableName = $("#arg1").val();
		var iscommonStr = $("#iscommonStr").val();
		var actObj = "";
		var fxActOnType = "";
		var argContentStr = "";
		var fxNameEnStr = $("#fxNameEnStr").val();
		var fxNameEn = '<%=FunctionAction.ADD_COL%>';
		var removeCol = '<%=FunctionAction.REMOVE_COL%>';
		var addPrefixToFileName = '<%=FunctionAction.ADD_PREFIX_TO_FILE_NAME%>';
		var addSuffixToFileName = '<%=FunctionAction.ADD_SUFFIX_TO_FILE_NAME%>';
		var setCurrentDate = '<%=FunctionAction.SET_CURRENTDATE%>'; 
		for(var i=0; i<argContentLength; i++){
			var temp = i;
			var paramV = "arg" + (temp + 1);
			var srcStr = "\${"+ paramV +"}";
			var descStr = $("#" + paramV).val();
			if(fxTypeStr =="1"){
				if(iscommonStr == "0"){
					if(i == 0){
						argContentStr = '{"' + paramV + '":"'+ descStr + '"}';
					}else{
						argContentStr += "," + '{"' + paramV + '":"'+ descStr + '"}';
					}
				}
			}
			if(fxTypeStr =="2" || fxTypeStr =="3"){
				if(iscommonStr == "0"){//批量修改表名
					if(i == 0){
						argContentStr = '{"tables":"'+ descStr + '"}';
					}else{
						argContentStr += "," + '{"arg' + (i) + '":"'+ descStr + '"}';
					}
				}else{
					if(i == 1){
						argContentStr = '{"arg' + (i) + '":"'+ descStr + '"}';
					}else if(i > 1){
						argContentStr += "," + '{"arg' + (i) + '":"'+ descStr + '"}';
					}
				}	
			}
			if(fxTypeStr =="4" || fxTypeStr =="5"){
				if(iscommonStr == "0"){
					if(fxNameEn == fxNameEnStr){
						if(i == 2){
							descStr = $("input[name='vrMethod']:checked").next().text();
						}else if(i == argContentLength-1){
							var vrFxId1 = $("#choosedFx").attr("fxId");
							if(vrFxId1 == "" || vrFxId1 == undefined || vrFxId1 == null){
								descStr = "字段值相等" ;
							}else{
								var vrArg = "";							
								if($("#arg4").val()!= null){
									vrArg = $("#arg4").val();
								}
								descStr = $("#choosedFx").text() + vrArg;
							}
						}
					}
					if(removeCol == fxNameEnStr){
						if(i == 0){//批量排除字段
							argContentStr = '{"tables":"'+ descStr + '"}';
						}else{
							argContentStr += ',{"arg' + (i) + '":"'+ descStr + '"}';
						}
					}else if(i == 1){//字段批量操作
						argContentStr = '{"arg' + (i) + '":"'+ descStr + '"}';
					}else{
						argContentStr += ',{"arg' + (i) + '":"'+ descStr + '"}';
					}
				}else{
					if(i == 2){
						argContentStr = '{"arg' + (i-1) + '":"'+ descStr + '"}';
					}else if(i > 2){
						argContentStr += ',{"arg' + (i-1) + '":"'+ descStr + '"}';
					}
				}
			}
			if(fxTypeStr =="6"){
				if(i == 2){
					argContentStr = '{"arg' + (i-1) + '":"'+ descStr + '"}';
				}else if(i > 2){
					argContentStr += "," + '{"arg' + (i-1) + '":"'+ descStr + '"}';
				}
			}						
			if(fxTypeStr =="7"){
				var fileFxId = $("#choosedFx").attr("fxId");
				var fileFxNameEn = $("#choosedFx").attr("fxNameEn");
				var fileAddMethod = $("input[name='fileAddMethod']:checked").attr("value");
				var fileFxName = $("#choosedFx").text();
				var dateFormat = $("#dateFormat").val();
				if(i == 0){
					argContentStr = '{"arg' + (i+1) + '":"'+ descStr + '"}';
				}else if(i > 0){
					argContentStr += "," + '{"arg' + (i+1) + '":"'+ descStr + '"}';
				}
				if(fxNameEnStr == addPrefixToFileName || fxNameEnStr == addSuffixToFileName){
					if(fileAddMethod == "0"){
						if(i == 0){
							mappingModel = mappingModel.replace(srcStr,"自定义");
						}
						if(i > 0){
						   argContentStr = '{"arg' + (i) + '":"'+ descStr + '"}';
						}
						argContentStr = argContentStr+',{"fileAddMethod":"'+fileAddMethod+'"},{"dateFormat":""}';
					}else{
						if(dateFormat != "" && dateFormat !="undefined" && dateFormat != null){
							if(i == 0){
								mappingModel = mappingModel.replace(srcStr,"设置默认值");
							}else{
								if(fileFxNameEn == setCurrentDate){
									mappingModel = mappingModel.replace(srcStr,"系统时间");
									mappingModel = mappingModel+"日期格式为"+dateFormat+"。";
								}
							}
						}else{
							if(i == 0){
								mappingModel = mappingModel.replace(srcStr,"设置默认值");
							}else{
								mappingModel = mappingModel.replace(srcStr,"");
							}
							fileFxId = '';
						}
						argContentStr = '{"arg1":""},{"fileAddMethod":"'+fileAddMethod+'"},{"dateFormat":"'+dateFormat+'"}';
					}
				}
			}
			mappingModel = mappingModel.replace(srcStr,descStr);
		}
		
		argContentStr = "["+argContentStr+"]";
		
		var tr_length =  window.content.document.getElementById("mappingRuleList").getElementsByTagName("tr").length;
		var ruleContent="";
	    if(fxTypeStr =="1"){//表操作
	    	if(iscommonStr == "0"){//非普通函数
	    		tableName = "";
	    		actObj = "";
	        	fxActOnType = "1";
	    	}
	    } 
	    if(fxTypeStr =="2" || fxTypeStr =="3"){//表名操作
	    	if(iscommonStr == "0"){
	    		tableName = "";
	    		actObj = "";
	        	fxActOnType = "1";
	    	}else{
	    		actObj = tableName;
	        	fxActOnType = "1";
	    	}
	    }
	 	if(fxTypeStr =="4" || fxTypeStr =="5"){//字段名操作
	 		if(iscommonStr == "0"){
	 			fxActOnType = "2";
	 	 		if(fxNameEnStr == fxNameEn){
	 	 			actObj = $("#arg2").val();
	 	 		}else if(removeCol == fxNameEnStr){
	 	 			tableName = "";
	 	 			actObj = "";
	 	 		}else{
	 	 			actObj = "";
	 	 		}
	 		}else{
	 			actObj = $("#arg2").val();
	 	 		fxActOnType = "2";
	 		}
	    }
		if(fxTypeStr =="6"){//字段值操作
			actObj = $("#arg2").val();
			fxActOnType = "3";
	    }
		if(fxTypeStr =="7"){//文件名操作
			tableName = "";
			actObj = "";
			fxActOnType = "4";
	    }
		if(fxNameEnStr == fxNameEn){//添加虚拟字段
			var vrMethod = $("input[name='vrMethod']:checked").attr("value");
			argContentStr = "";
			var vrFxId = $("#choosedFx").attr("fxId");
			var vrFxName = $("#choosedFx").text();
			if(vrMethod == "0"){
				 for(var x=0;;x++){
					var keyV = "arg" + (x+1);
					var param = "arg" + (x+4);
					var paramV = $("#"+param).val();
					if(paramV != null){
						if(x == 0){
							argContentStr += '{"'+ keyV +'":"'+ paramV + '"}';
						}else{
							argContentStr += ',{"'+ keyV +'":"'+ paramV + '"}';
						}
						
					}else{
						break;
					}
				} 
				argContentStr = '['+ argContentStr +']';
				argContentStr = '{"vrType":"'+vrMethod+'","fxId":"'+vrFxId+'","fxName":"'+vrFxName+'","args":'+argContentStr+'}';
			}else{
				var key = $("#arg3").val();
				var vrRule = $("#arg4").val();
				var vrRuleStr = "";
				if(vrRule != null){
					vrRuleStr = ',"args":{"arg":"'+vrRule+'"}';
				}
				if(vrFxId == "" || vrFxId == undefined || vrFxId == null){
					argContentStr = '{"vrType":"'+vrMethod+'","col":"'+key+'"}';//字段值相加
				}else{
					argContentStr = '{"vrType":"'+vrMethod+'","fxId":"'+vrFxId+'","fxName":"'+vrFxName+'","col":"'+key+'"'+vrRuleStr+'}';
				}
			}
		}
		var paramStr = "";
		if (fxTypeStr != "7") {
			paramStr = '<tr tableName="'+tableName+'" actObj="'+actObj+'" fxName="'+fxNameEnStr+'" fxId="'+fxIdStr+'" argContent='+argContentStr+' fxActOnType="'+fxActOnType+'">'
				+'	<td class="center">'+tr_length+'</td>'
  				+'  <td>'+mappingModel+'</td>';
		} else {
			paramStr = '<tr fxName="'+fxNameEnStr+'" fxId="'+fxIdStr+'" argContent='+argContentStr+' fxActOnType="'+fxActOnType+'">'
			+'	<td class="center">'+tr_length+'</td>'
				+'  <td>'+mappingModel+'</td>';
		}
	 	ruleContent= paramStr
	  				+'  <td class="center">'
	  				+'		<div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">'
	  				+'  		<a class="red" href="javascript:void(0)" onclick="deleteFxMapping(this);" title="删除">'
					+'   			<i class="icon-trash bigger-130"></i>'
					+'  		</a>'
					+'		</div>'
	  				+' </td>'
	 				+'</tr>';
					
		ruleContent = $(window.content.document.getElementById("mappingRuleList")).find("table tbody").html() + ruleContent;
	    $(window.content.document.getElementById("mappingRuleList")).find("table tbody").html(ruleContent);
	    $(window.content.document.getElementById("mappingRuleList")).css("display","");
	    parent.setIframeHeight(parent.document.getElementById("content"));//设置iframe高度
	    $('#dataMappingRuleAddModal').modal('hide');
	    if(window.content.$('input[name="mappingType"]:checked').val() == '3'){
	    	window.content.$("#sbmDiv").css("display","");
	    }
	}
}
/**
 * 改变表信息(即选择不同的表)
 */
function changeTableInfo(tableNameOption){//触发表
	//var tableName = $("#arg1").val();
	$("#arg2").empty(); //置空
	var fxNameEnStr = $("#fxNameEnStr").val();
	var iscommonStr = $("#iscommonStr").val();
	var fxTypeStr = $("#fxTypeStr").val();
	var tableName = $(tableNameOption).find("option:selected").val();
	var tabNames = $(tableNameOption).val();
	var fxNameEn = '<%=FunctionAction.ADD_COL%>';//添加虚拟字段
	var removeCol = '<%=FunctionAction.REMOVE_COL%>';
	if(tabNames != "" && tabNames != null && tabNames != undefined && fxNameEnStr != fxNameEn){
		if(fxNameEnStr == removeCol){
			var tabColMap = $("#tabColMap").val();
			var tablecolOption = "";
			if(iscommonStr != "0"){
				tablecolOption = "<option value=''>请选择字段</option>";
			}
			var tabMapNew = {};
			for(var i = 0; i < tabNames.length; i++){
				var tabColList = eval("JSON.parse(tabColMap)." + tabNames[i]);
				var tabColMapNew = {};
				if(tabColList != "" && tabColList != null && tabColList != undefined){
					for(var j = 0 ; j < tabColList.length; j++){
						tabColMapNew[tabColList[j].colName] = tabColList[j];
					}
					tabMapNew[tabNames[i]] = tabColMapNew;
				}
			}
			if(tabNames.length > 0 ){
				var tabColList = eval("JSON.parse(tabColMap)." + tabNames[0]);
				if(tabNames.length <= 1){
					if(tabColList != "" && tabColList != null && tabColList != undefined){
						for(var j = 0;j<tabColList.length;j++){
							tablecolOption += "<option value='"+tabColList[j].colName+"'>"+tabColList[j].colName +"</option>";
						}
					}
				}else{
					if(tabColList != "" && tabColList != null && tabColList != undefined){
						for(var j = 0;j < tabColList.length;j++){
							var colName = tabColList[j].colName;
							var sameFlag = true;
							$.each(tabMapNew, function(key, val) {
								var tabCols = val;
								if(tabCols[colName] != "" && tabCols[colName] != null && tabCols[colName] != "undefined"){
									sameFlag = sameFlag && true;
								}else{
									sameFlag = sameFlag && false;
								}
							});
							if(sameFlag){
								tablecolOption += "<option value='"+colName+"'>"+colName +"</option>";
							}
						}
					}
				}
			}
			//字段列下拉列表设置
			$("#arg2").prop("selectedIndex", 0);
			$("#arg2").html(tablecolOption); 
		}else{
			var tabColMap = $("#tabColMap").val();
			var tabColList = eval("JSON.parse(tabColMap)." + tableName);	
			var tablecolOption = "";
			if(iscommonStr != "0"){
				tablecolOption = "<option value=''>请选择字段</option>";
			}
			if(tabColList != "" && tabColList != null && tabColList != undefined){
				for(var j = 0;j<tabColList.length;j++){
					tablecolOption += "<option value='"+tabColList[j].colName+"'>"+tabColList[j].colName +"</option>";
				}
			}
			//字段列下拉列表设置
			$("#arg2").prop("selectedIndex", 0);
			$("#arg2").html(tablecolOption); 
		}
	}else{
		var tabColMap = $("#tabColMap").val();
		var tabColList = eval("JSON.parse(tabColMap)." + tableName);	
		var tablecolOption = "<option value=''>请选择字段</option>";
		if(tabColList != "" && tabColList != null && tabColList != undefined){
			for(var j = 0;j<tabColList.length;j++){
				tablecolOption += "<option value='"+tabColList[j].colName+"'>"+tabColList[j].colName +"</option>";
			}
		}
		//字段列下拉列表设置
		$("#arg3").prop("selectedIndex", 0);
		$("#arg3").html(tablecolOption); 
	}
	if(fxNameEnStr == removeCol){
		if(tabNames != "" && tabNames != null && tabNames != undefined && fxNameEnStr != fxNameEn){
			for(var i=0;i<tabNames.length;i++){
				verifyHandleCol(tabNames[i]);//排除字段
			}
		}
	}else{
		verifyHandleCol(tableName);//排除字段
	}
	activateSelect(iscommonStr,fxTypeStr,fxNameEnStr);//激活select
}

/**
 * 校验处理
 */
function verifyHandle(){
	var tableInfo = $(window.content.document.getElementById("mappingRuleList")).find("table tbody tr");
	var trLength = tableInfo.length;
	var removeTab = '<%=FunctionAction.REMOVE_TABLE%>';//排除表

	var addCol = '<%=FunctionAction.ADD_COL%>';//添加虚拟字段
	var removeTabStr = "";
	for(var i=0; i<trLength; i++){
		var trInfo = tableInfo[i];
		var fxName = trInfo.getAttribute("fxName");
		if(removeTab == fxName){
			var argContent = trInfo.getAttribute("argContent");
			argContent = $.parseJSON(eval(JSON.stringify(argContent)));
			if(removeTabStr == ""){
				removeTabStr += argContent[0].arg1;
			}else{
				removeTabStr += "," + argContent[0].arg1;
			}
		}
	}
	if(removeTabStr != ""){
		var removeTabArr = removeTabStr.split(",");
		for(var i=0;i<removeTabArr.length;i++){
			$("select[name='tableObject']").find("option[value="+removeTabArr[i]+"]").css("display","none");
		}
	}
	/* verifyHandleCol(tableName);//排除字段 */
}

/**
 * 表字段校验处理
 */
function verifyHandleCol(tableName){
	var tableInfo = $(window.content.document.getElementById("mappingRuleList")).find("table tbody tr");
	var trLength = tableInfo.length;
	var removeCol = '<%=FunctionAction.REMOVE_COL%>';//排除字段
	var removeColStr = "";
	for(var i=0; i<trLength; i++){
		var trInfo = tableInfo[i];
		var fxName = trInfo.getAttribute("fxName");
		var tbName = trInfo.getAttribute("tableName");
		var argContent = trInfo.getAttribute("argContent");
		argContent = $.parseJSON(eval(JSON.stringify(argContent)));
		
		if(removeCol == fxName){
			tbName = argContent[0].tables;
			tbName = tbName.split(",");
			for(var j=0; j<tbName.length; j++){
				if(tbName[j] == tableName){
					if(removeColStr == ""){
						removeColStr += argContent[1].arg1;
					}else{
						removeColStr += "," + argContent[1].arg1;
					}
					break;
				}
			}
		}
	}
	if(removeColStr != ""){
		var removeColArr = removeColStr.split(",");
		for(var i=0;i<removeColArr.length;i++){
			$("select[name='colList']").find("option[value="+removeColArr[i]+"]").css("display","none");
		}
	}
}

/**
 * 多选下拉列表激活
 */
function activateSelect(iscommon,fxType,fxNameEn){
	var fxNameEnStr = '<%=FunctionAction.ADD_COL%>';
	if(iscommon == "0"){
		if(fxType == "1" || (fxType == "2" || fxType == "3")){
			$('#arg1').selectpicker({  
		         style: 'btn-info'
			});
			$("#arg1").selectpicker({noneSelectedText:'请选择'});
			//$('#arg1').selectpicker('val', '');
			$('#arg1').selectpicker('refresh');
		}
		if((fxType == "4" || fxType == "5") && fxNameEn != fxNameEnStr){
			var removeCol = '<%=FunctionAction.REMOVE_COL%>';
			if(fxType == "5" && fxNameEn == removeCol){
				$('#arg1').selectpicker({  
			         style: 'btn-info'
				});
				$("#arg1").selectpicker({noneSelectedText:'请选择'});
				$('#arg1').selectpicker('refresh');
			}
			$('#arg2').selectpicker({  
		         style: 'btn-info' 
			});
			$("#arg2").selectpicker({noneSelectedText:'请选择字段'});
			$('#arg2').selectpicker('refresh');
		}
		$(".bootstrap-select.btn-group[class*=col-] .dropdown-toggle").css("width","108%");
		$(".bootstrap-select.btn-group[class*=col-] .dropdown-toggle").css("margin-left","-11px");
	}
}

/* validator={
	tableName：	
} */
</script>
<a class="btn btn-success btn-xs mg-top12 mg-left12" style="margin-left: 24px;" onclick="dataMappingRuleChoose()" >
	<i class="icon-plus-sign icon-on-right"></i> 选择映射规则&nbsp;&nbsp;
</a>
<div class="table-responsive">
	<div class="row">
		<div class="col-xs-12">
			<div class="widget-main">
			<form class="form-horizontal" role="form" id="inputForm" action="" method="post">
			    <input id="srcDsId" name="srcDsId" value="${param.srcDsId }" hidden="">
				<div class="profile-user-info profile-user-info-striped" id="mapping_rule">
					<!-- <div class="profile-info-row">
						<div class="profile-info-name">已选择规则</div>
						<div class="profile-info-value">
							<span class="editable">&nbsp;</span>
						</div>
					</div>
					<div class="profile-info-row">
						<div class="profile-info-name">将要截取的表名</div>
						<div class="profile-info-value">
							<span class="editable">&nbsp;</span>
						</div>
					</div>
					<div class="profile-info-row">
						<div class="profile-info-name">截取起始位置</div>
						<div class="profile-info-value">
							<span class="editable">&nbsp;</span>
						</div>
					</div>
					<div class="profile-info-row">
						<div class="profile-info-name">截取字符长度</div>
						<div class="profile-info-value">
							<span class="editable">&nbsp;</span>
						</div>
					</div>
					<div class="profile-info-row">
						<div class="profile-info-name">截取后的表名</div>
						<div class="profile-info-value">
							<span class="editable">&nbsp;</span>
						</div>
					</div> -->
				</div>
			    <div class="widget-toolbar no-border">
			    	<button class="btn btn-info btn-xs" id="saveBtn" type="button" onclick="saveInfo()"><i class="icon-ok bigger-110"></i>保存&nbsp;&nbsp;</button>
			        <button class="btn btn-primary btn-xs" type="button" onclick="$('#dataMappingRuleAddModal').modal('hide');"><i class="icon-remove"></i> 取消&nbsp;&nbsp;</button>
			    </div>
			   </form>
			</div>
		</div>
	</div>
</div>
